package com.sb.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by wujunzhou on 2017/10/25.
 */
public class JSONHandler implements TypeHandler<Object> {
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Object o, JdbcType jdbcType) throws SQLException {
        if(o == null){
            preparedStatement.setString(i, null);
            return;
        }
        String json = JSON.toJSONString(o);
        preparedStatement.setString(i, json);
    }

    @Override
    public Object getResult(ResultSet resultSet, String s) throws SQLException {
        String  json = resultSet.getString(s);
        return  jsonToObject(json);
    }

    @Override
    public Object getResult(ResultSet resultSet, int i) throws SQLException {
        return null;
    }

    @Override
    public Object getResult(CallableStatement callableStatement, int i) throws SQLException {
        String  json = callableStatement.getString(i);
        return  jsonToObject(json);
    }
    /**
     * json 转换成对象
     * */
    private Object jsonToObject(String json){
        if(json == null){
            return null;
        }

        Object ob = JSONObject.parse(json);
        return ob;
    }
}
